package asher.dotatbg.http.responser;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import asher.dotatbg.constants.Constants;
import asher.dotatbg.http.configs.MainConfig;
import asher.dotatbg.logfactory.LogFactory;
import asher.dotatbg.util.ClassFinder;

/**
 * 动态资源库
 * 完成对动态请求的解析和具体服务类的调用
 * @author AsherYuan
 *
 */
public class ServiceRepository {

	private Logger logger = LogFactory.getRootLogger();
	private OutputStream output;
	
	public ServiceRepository(OutputStream output) {
		this.output = output;
	}
	
	public void sendServiceResult(String uri) throws IOException {
		String serviceName = uri.substring(uri.lastIndexOf("/") + 1);
		URLClassLoader loader = null;
		try {
			URL[] urls = new URL[1];
			URLStreamHandler streamHandler = null;
			File classPath = new File(Constants.WEB_ROOT);
			String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
			urls[0] = new URL(null, repository, streamHandler);
			loader = new URLClassLoader(urls);
		} catch (IOException e) {
			logger.info("服务资源库，获取服务类失败  " + "........." + new Date().toString());
		}
		
		List<Map<String, String>> classList = ClassFinder.findClasses(new ArrayList<Map<String, String>>(), MainConfig.getInstance().defalutResponserPackage, true);
		
		for(Map<String, String> map : classList) {
			String className = map.get("className");
			String packageName = map.get("packageName");
			packageName = packageName.replace("/", ".");
			if(className.equals(serviceName)) {
				Class<?> myClass = null;
				try {
					myClass = loader.loadClass(packageName + "." + serviceName);
				} catch (ClassNotFoundException e) {
					logger.info("服务资源库，创建服务类失败  " + "........." + new Date().toString());
				}

				Responser responser = null;
				try {
					responser = (Responser) myClass.newInstance();
					responser.service(output);
				} catch (Exception e) {
					System.out.println(e.toString());
				} catch (Throwable e) {
					System.out.println(e.toString());
				}
			}
		}
	}
}
